package com.yx.changdao.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yx.changdao.common.annotation.AutoLog;
import com.yx.changdao.common.annotation.ShiroDesc;
import com.yx.changdao.common.data.Pager;
import com.yx.changdao.common.data.Result;
import com.yx.changdao.common.data.ResultCodeEnum;
import com.yx.changdao.common.entity.*;
import com.yx.changdao.common.exception.AlertException;
import com.yx.changdao.common.utils.Faster;
import com.yx.changdao.common.utils.SysConst;
import com.yx.changdao.common.utils.SysUtils;
import com.yx.changdao.common.valid.Default;
import com.yx.changdao.common.valid.Update;
import com.yx.changdao.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 部门联户人小组
 * <p>
 *
 * @Auther: zcz
 * @create 2020/04/30 11:26
 */
@Validated
@RestController
@RequestMapping("dep/contact/group")
public class DepContactGroupController {

    /**
     * 部门联户人小组服务
     */
    @Autowired
    private DepContactGroupService depContactGroupService;
    /**
     * 工作人员服务
     */
    @Autowired
    private DepWorkerService depWorkerService;
    /**
     * 工作人员服务
     */
    @Autowired
    private CommunityBuildDetailService communityBuildDetailService;

    /**
     * 用户服务
     */
    @Autowired
    private SysUserService sysUserService;

    /**
     * 建筑物服务
     */
    @Autowired
    private CommunityBuildService communityBuildService;

    /**
     * 建筑物联户组关联服务
     */
    @Autowired
    private ContactGroupBuildService contactGroupBuildService;

    /**
     * 列表 执行部门
     *
     * @return Result
     */
    @AutoLog
    @GetMapping("/list")
    @RequiresPermissions("dep:contact:group:list")
    @ShiroDesc("联户组管理（执行部门）:列表")
    public Result list(@RequestParam(value = "page") Long page,
                       @RequestParam(value = "limit", required = false) Integer limit) throws AlertException {
        if (limit == null) {
            limit = SysConst.LIMIT_PAGE;
        }
        // 分页配置
        Page<DepContactGroup> pager = new Page<>(page, limit);
        // 根据请求解析条件。
        QueryWrapper<DepContactGroup> cnd = SysUtils.autoCnd(DepContactGroup.class);
        cnd.eq(DepContactGroup.DEP_ID, SysUtils.currentUser().getDepId());

        // 获取分页结果集。
        Page<DepContactGroup> dealPage = this.depContactGroupService.page(pager, cnd);
        // 小组下人员
        dealPage.getRecords().forEach(d -> {
            QueryWrapper<DepWorker> wrapper = new QueryWrapper<DepWorker>().eq(DepWorker.CONTACT_GROUP_ID, d.getContactGroupId());
            int count = depWorkerService.count(wrapper);
            d.setWorkerCount(count);
        });
        Map<String, Object> map = new HashMap<>();
        map.put("list", dealPage.getRecords());
        map.put("pager", new Pager(dealPage));
        return Result.ok().data(map);
    }

    /**
     * 列表 总控部门
     *
     * @return Result
     */
    @AutoLog
    @GetMapping("/zk/list")
    @RequiresPermissions("dep:contact:group:zkbm:list")
    @ShiroDesc("联户组管理（总控部门）:列表")
    public Result list2(@RequestParam(value = "page") Long page,
                        @RequestParam(value = "limit", required = false) Integer limit) throws AlertException {
        if (limit == null) {
            limit = SysConst.LIMIT_PAGE;
        }

        // 分页配置
        Page<DepContactGroup> pager = new Page<>(page, limit);
        // 根据请求解析条件。
        QueryWrapper<DepContactGroup> cnd = SysUtils.autoCnd(DepContactGroup.class);
        // 获取分页结果集。
        Page<DepContactGroup> dealPage = this.depContactGroupService.page(pager, cnd);
        // 小组下人员
        dealPage.getRecords().forEach(d -> {
            QueryWrapper<DepWorker> wrapper = new QueryWrapper<DepWorker>().eq(DepWorker.CONTACT_GROUP_ID, d.getContactGroupId());
            int count = depWorkerService.count(wrapper);
            d.setWorkerCount(count);
        });

        Map<String, Object> map = new HashMap<>();
        map.put("list", dealPage.getRecords());
        map.put("pager", new Pager(dealPage));
        return Result.ok().data(map);
    }

    /**
     * 根据小组id查询小组下成员  不分页
     *
     * @param contactGroupId
     * @return
     */
    @AutoLog
    @GetMapping("/dep/work/list")
    public Result list(@RequestParam(value = "contactGroupId") Long contactGroupId) {
        // 根据请求解析条件。
        QueryWrapper<DepWorker> cnd = SysUtils.autoCnd(DepWorker.class);
        cnd.eq(DepWorker.CONTACT_GROUP_ID, contactGroupId);
        List<DepWorker> list = depWorkerService.list(new QueryWrapper<DepWorker>().eq(DepWorker.CONTACT_GROUP_ID, contactGroupId));
        DepContactGroup depContactGroup = depContactGroupService.getOne(new QueryWrapper<DepContactGroup>().eq(DepContactGroup.CONTACT_GROUP_ID, contactGroupId));
        Map<String, Object> date = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        if (!Faster.isNull(depContactGroup)) {
            map.put("depName", depContactGroup.getDepName());
            map.put("groupName", depContactGroup.getGroupName());
        }
        date.put("list", list);
        date.put("name", map);
        return Result.ok().data(date);
    }

    /**
     * 添加部门联户人小组
     *
     * @param
     * @return Result
     */
    @AutoLog
    @PostMapping
//    @RequiresPermissions("dep:contact:group:add")
//    @ShiroDesc("部门联户人小组:添加")
    public Result add(@RequestBody @Validated(Default.class) DepContactGroup depContactGroup) throws AlertException {
        int dgCount = depContactGroupService.count(new QueryWrapper<DepContactGroup>()
                .eq(DepContactGroup.GROUP_NAME, depContactGroup.getGroupName()));
        if (0 < dgCount) {
            throw new AlertException("小组名称已存在");
        }
        depContactGroup.setDepId(SysUtils.currentUser().getDepId());
        depContactGroup.setDepName(SysUtils.currentUser().getDepName());
        boolean b = depContactGroupService.save(depContactGroup);
        if (!b) {
            throw new AlertException("部门联户人小组添加失败");
        }
        return Result.ok("部门联户人小组添加成功");
    }


    /**
     * 获得指定id 部门联户人小组。
     *
     * @param
     * @return Result
     */
    @AutoLog
    @GetMapping("/{id}")
//    @RequiresPermissions("dep:contact:group:look")
//    @ShiroDesc("部门联户人小组:查看")
    public Result get(@PathVariable("id") String id) throws AlertException {
        DepContactGroup depContactGroup = depContactGroupService.getById(id);
        if (depContactGroup == null) {
            throw new AlertException("未找到相关部门联户人小组信息");
        }
        return Result.ok().data(depContactGroup);
    }


    /**
     * 更新部门联户人小组
     *
     * @param
     * @return Result
     */
    @AutoLog
    @PutMapping
//    @RequiresPermissions("dep:contact:group:save")
//    @ShiroDesc("部门联户人小组:保存")
    public Result update(@RequestBody @Validated(Update.class) DepContactGroup depContactGroup) throws AlertException {
        int dgCount = depContactGroupService.count(new QueryWrapper<DepContactGroup>()
                .eq(DepContactGroup.GROUP_NAME, depContactGroup.getGroupName())
                .ne(DepContactGroup.CONTACT_GROUP_ID, depContactGroup.getContactGroupId()));
        if (0 < dgCount) {
            throw new AlertException("小组名称已存在");
        }
        UpdateWrapper<DepContactGroup> updateWrapper = new UpdateWrapper<DepContactGroup>()
                .set(DepContactGroup.GROUP_NAME, depContactGroup.getGroupName())
                .set(DepContactGroup.UPDATE_BY, SysUtils.currentUserId())
                .set(DepContactGroup.UPDATE_BY_NAME, SysUtils.currentUserName())
                .set(DepContactGroup.UPDATE_TIME, Faster.now()).eq(DepContactGroup.CONTACT_GROUP_ID, depContactGroup.getContactGroupId());
        boolean b = depContactGroupService.update(updateWrapper);
        if (!b) {
            throw new AlertException("部门联户人小组更新失败");
        }
        // 同步更新户信息表中的联户人组信息
        UpdateWrapper<CommunityBuildDetail> uw = new UpdateWrapper<CommunityBuildDetail>()
                .set(CommunityBuildDetail.GROUP_NAME, depContactGroup.getGroupName())
                .eq(CommunityBuildDetail.CONTACT_GROUP_ID, depContactGroup.getContactGroupId());
        communityBuildDetailService.update(uw);
        return Result.ok("部门联户人小组更新成功");
    }


    /**
     * 删除部门联户人小组
     *
     * @param
     * @return Result
     */
    @AutoLog
    @DeleteMapping()
//    @RequiresPermissions("dep:contact:group:del")
//    @ShiroDesc("部门联户人小组:删除")
    @Transactional(rollbackFor = {Exception.class})
    public Result delete(@RequestParam("contactGroupId") String contactGroupId) throws AlertException {
        int count = communityBuildDetailService.count(new QueryWrapper<CommunityBuildDetail>()
                .eq(CommunityBuildDetail.CONTACT_GROUP_ID, contactGroupId));
        if (0 < count) {
            return Result.ok("联户人小组已关联户，无法删除", ResultCodeEnum.ERROR);
        }
        // 删除小组成员
        depWorkerService.remove(new QueryWrapper<DepWorker>().eq(DepWorker.CONTACT_GROUP_ID, contactGroupId));
        // 删除小组
        boolean b = depContactGroupService.removeById(contactGroupId);
        if (!b) {
            throw new AlertException("部门联户人小组删除失败");
        }
        return Result.ok("删除成功");
    }

    /**
     * 下拉列表
     *
     * @return Result
     */
    @AutoLog
    @GetMapping("/select")
//    @RequiresPermissions("dep:contact:group:groupselect")
//    @ShiroDesc("部门联户人小组:根据部门查询分组列表")
    public Result select(String depId) {
        List<DepContactGroup> collect = new ArrayList<>();
        if (StringUtils.isEmpty(depId)) {
            return Result.ok().data(collect);
        }
        List<DepContactGroup> list = depContactGroupService.
                list(new QueryWrapper<DepContactGroup>().eq(DepContactGroup.DEP_ID, depId));

        collect = list.stream().filter(t -> {
            return depWorkerService.count(new QueryWrapper<DepWorker>()
                    .eq(DepWorker.CONTACT_GROUP_ID, t.getContactGroupId())
                    .eq(DepWorker.DEP_ID, t.getDepId())) > 0 ? true : false;
        }).collect(Collectors.toList());

        return Result.ok().data(collect);
    }

    /**
     * 获取联户组关联/未关联的账号
     *
     * @return Result
     */
    @AutoLog
    @GetMapping("/link/account/list")
    public Result linkList(@RequestParam("contactGroupId") String contactGroupId, @RequestParam(value = "userName", required = false) String userName) {
        if (StringUtils.isEmpty(contactGroupId)) {
            return Result.error("联户组id不能为空");
        }
        DepContactGroup depContactGroup = depContactGroupService.getOne(new QueryWrapper<DepContactGroup>().eq(DepContactGroup.CONTACT_GROUP_ID, contactGroupId));
        if (null == depContactGroup) {
            return Result.error("未查询到联户组信息");
        }
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<SysUser>().eq(SysUser.DEP_ID, depContactGroup.getDepId()).orderByAsc(SysUser.CREATE_TIME).orderByAsc(SysUser.USERNAME);
        // 暂时不用，看前端能不能自己筛选
//        if (!Strings.isBlank(userName)) {
//            sysUserQueryWrapper.like(SysUser.USERNAME, userName);
//        }
        List<SysUser> userList = sysUserService.list(sysUserQueryWrapper);
        List<SysUser> linkList = new ArrayList<>();
        List<SysUser> noLinkList = new ArrayList<>();
        for (SysUser sysUser : userList) {
            if (sysUser.getContactGroupId() != null && sysUser.getContactGroupId().intValue() == depContactGroup.getContactGroupId()) {
                linkList.add(sysUser);
            } else {
                noLinkList.add(sysUser);
            }
        }
        Map<String, Object> param = new HashMap<>();
        param.put("link", linkList);
        param.put("nolink", noLinkList);
        param.put("alllink", userList);
        return Result.ok().data(param);
    }

    /**
     * 关联账号
     *
     * @return Result
     */
    @AutoLog
    @PutMapping("/link/account/{contactGroupId}")
    public Result linkAccount(@PathVariable("contactGroupId") String contactGroupId, @RequestParam("userIds") String userIds) throws AlertException {
        if (StringUtils.isEmpty(contactGroupId)) {
            throw new AlertException("联户组id不能为空");
        }
        String[] ids = userIds.split(",");
        List<SysUser> addUserList = sysUserService.list(new QueryWrapper<SysUser>().in(SysUser.USER_ID, ids));
        depContactGroupService.contactLinkAccount(contactGroupId, addUserList);
        return Result.ok("关联账号成功");
    }

    /**
     * 取消关联账号
     *
     * @return Result
     */
    @AutoLog
    @PutMapping("/noLink/account/{contactGroupId}")
    public Result noLinkAccount(@PathVariable("contactGroupId") String contactGroupId, @RequestParam("userIds") String userIds) throws AlertException {
        if (StringUtils.isEmpty(contactGroupId)) {
            throw new AlertException("联户组id不能为空");
        }
        String[] ids = userIds.split(",");
        List<SysUser> addUserList = sysUserService.list(new QueryWrapper<SysUser>().in(SysUser.USER_ID, ids));
        depContactGroupService.noContactLinkAccount(contactGroupId, addUserList);
        return Result.ok("取消关联账号成功");
    }


    /**
     * 获取联户组关联/未关联的楼
     *
     * @return Result
     */
    @AutoLog
    @GetMapping("/link/build/list")
    public Result linkBuildList(@RequestParam("contactGroupId") String contactGroupId, @RequestParam(value = "buildName", required = false) String buildName) throws AlertException {
        if (StringUtils.isEmpty(contactGroupId)) {
            throw new AlertException("联户组id不能为空");
        }
        DepContactGroup depContactGroup = depContactGroupService.getOne(new QueryWrapper<DepContactGroup>().eq(DepContactGroup.CONTACT_GROUP_ID, contactGroupId));
        if (null == depContactGroup) {
            return Result.error("未查询到联户组信息");
        }
        QueryWrapper<CommunityBuild> communityBuildQueryWrapper = new QueryWrapper<CommunityBuild>().eq(CommunityBuild.DEP_ID, depContactGroup.getDepId()).orderByAsc(CommunityBuild.BUILD_NAME);
        if (!Strings.isBlank(buildName)) {
            communityBuildQueryWrapper.like(CommunityBuild.BUILD_NAME, buildName);
        }
        List<CommunityBuild> buildList = communityBuildService.list(communityBuildQueryWrapper);//部门下所有的建筑物
        //所有的联户组关联的楼
        List<ContactGroupBuild> contactGroupBuildList = contactGroupBuildService.list(new QueryWrapper<ContactGroupBuild>().eq(ContactGroupBuild.CONTACT_GROUP_ID, contactGroupId));
        List<CommunityBuild> linkList = new ArrayList<>();
        List<CommunityBuild> noLinkList = new ArrayList<>();
        for (CommunityBuild build : buildList) {// 循环所有的建筑物
            boolean hasLink = false;
            for (ContactGroupBuild contactGroupBuild : contactGroupBuildList) {// 循环所有的中间表，确认楼关联关系
                if (build.getId() != null && build.getId().intValue() == contactGroupBuild.getBuildId()) {
                    hasLink = true;
                }
            }
            if (hasLink) {
                linkList.add(build);
            } else {
                noLinkList.add(build);
            }
        }
        Map<String, Object> param = new HashMap<>();
        param.put("link", linkList);
        param.put("nolink", noLinkList);
        param.put("alllink", buildList);
        return Result.ok().data(param);
    }


    /**
     * 关联楼
     *
     * @return Result
     */
    @AutoLog
    @PutMapping("/link/build/{contactGroupId}")
    @Transactional(rollbackFor = {Exception.class})
    public Result linkBuild(@PathVariable("contactGroupId") String contactGroupId, @RequestParam("buildIds") String buildIds) throws AlertException {
        if (StringUtils.isEmpty(contactGroupId)) {
            throw new AlertException("联户组id不能为空");
        }
        String[] ids = buildIds.split(",");
        List<CommunityBuild> buildList = communityBuildService.list(new QueryWrapper<CommunityBuild>().in(CommunityBuild.ID, ids));
        depContactGroupService.contactLinkBuild(contactGroupId, buildList);
        return Result.ok("关联楼成功");
    }
    /**
     * 取消关联楼
     *
     * @return Result
     */
    @AutoLog
    @PutMapping("/noLink/build/{contactGroupId}")
    @Transactional(rollbackFor = {Exception.class})
    public Result noLinkBuild(@PathVariable("contactGroupId") String contactGroupId, @RequestParam("buildIds") String buildIds) throws AlertException {
        if (StringUtils.isEmpty(contactGroupId)) {
            throw new AlertException("联户组id不能为空");
        }
        String[] ids = buildIds.split(",");
        List<CommunityBuild> buildList = communityBuildService.list(new QueryWrapper<CommunityBuild>().in(CommunityBuild.ID, ids));
        depContactGroupService.noContactLinkBuild(contactGroupId, buildList);
        return Result.ok("取消关联楼成功");
    }
}
